package org.squabble.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.squabble.domain.Comment;

@Repository
public class CommentDAOImpl extends AbstractHibernateDAO<Comment> implements
		CommentDAO {

	private final Log log = LogFactory.getLog(this.getClass());

	@Autowired
	public CommentDAOImpl(SessionFactory sessionFactory) {
		super(Comment.class, sessionFactory);
	}

	@Override
	public Comment getComment(Long id) {
		Comment comment = (Comment) get(id);
		log.debug("Loaded: " + comment);
		return comment;
	}

	@Override
	public List<Comment> getComments() {
		Criteria c = criteria();
		c.add(Restrictions.isNull("parent"));
		c.addOrder(Order.desc("lastReplyDate"));
		List<Comment> comments = list(c);
		return comments;
	}

	@Override
	public void save(Comment comment) {
		currentSession().saveOrUpdate(comment);
	}

}
